var express = require("express");
var router = express.Router();

router.get("/openid", async function (req, res) {
  // 小程序后台中获取
  const appId = "";
  const appSecret = "";

  // 先调用wx.getUserProfile获取权限，再通过uni.login获取到res.code -> code
  let { code } = req.query;

  try {
    const response = await axios.get(
      "https://api.weixin.qq.com/sns/jscode2session",
      {
        params: {
          appid: appId,
          secret: appSecret,
          js_code: code,
          grant_type: "authorization_code",
        },
      }
    );
    res.send({
      code: 0,
      data: response.data.openid,
      message: "user OpenId",
    });
  } catch (err) {
    res.send({
      code: 0,
      message: "get OpenId Fail",
    });
  }
});

module.exports = router;
